package com.example.app1.util;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;

import com.example.app1.LogUtil;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * 这是tts播放线程，通过共享缓存与主线程交互
 */
public class HandleTts {
    private static final String TAG = "PlayThread";
    private final SharedPreferences sharedPreferences;
    private final TextToSpeech textToSpeech;
    private boolean doingSign = false;
    private UtteranceProgressListener progressListener = null;
    Queue<String[]> textQueue;  // string[]内容：[0:idx, 1:text播放内容, 2:currentItemId当前id,3:currentTitle当前标题,
    // 4:currentItemContent(jsonArray) 当前章节全部内容, 5:nextItemId下一章id, 6:preId上一章节Id]

    public HandleTts(SharedPreferences sharedPreferences, TextToSpeech textToSpeech) {
        textQueue = new ArrayDeque<>();
        this.sharedPreferences = sharedPreferences;
        this.textToSpeech = textToSpeech;
        this.progressListener = new UtteranceProgressListener() {
            @Override
            public void onStart(String utteranceId) {
                // 文本朗读开始时调用
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString(CacheKey.STATUS.name(), PlayStatus.PLAYING.name());  // 更新状态为播放中
                edit.putString(CacheKey.READY_STATUS.name(), "");  // 更新预备状态为空
                edit.putBoolean(CacheKey.Show_PAUSE.name(), true);  // 更新暂停按钮状态为显示
                edit.apply();
//                    LogUtil.info(TAG, "onStart " + (currentIndex + 1) + "/" + contents.length);
            }

            @Override
            public void onDone(String utteranceId) {
                // 文本朗读完成时调用
//                    LogUtil.info(TAG, "onDone " + (currentIndex + 1) + "/" + contents.length);
                tryPlayNextText();
            }

            @Override
            public void onError(String utteranceId) {
                // 发生错误时调用
                LogUtil.info(TAG, "onError " + utteranceId);
            }

            @Override
            public void onStop(String utteranceId, boolean interrupted) {
                // 文本朗读被停止时调用
                LogUtil.info(TAG, "onStop " + utteranceId + " interrupted:" + interrupted);

                String readyStatus = sharedPreferences.getString(CacheKey.READY_STATUS.name(), "");
                SharedPreferences.Editor edit = sharedPreferences.edit();
                if (readyStatus.equals(PlayStatus.PAUSE.name())) {
                    edit.putString(CacheKey.STATUS.name(), PlayStatus.PAUSE.name());  // 更新状态为已暂停
                } else {
                    edit.putString(CacheKey.STATUS.name(), PlayStatus.STOP.name());  // 更新状态为已停止
                }
                edit.putString(CacheKey.READY_STATUS.name(), "");  // 更新预备状态为空
                edit.putBoolean(CacheKey.Show_PAUSE.name(), false);  // 更新暂停按钮显示状态
                edit.apply();
                doingSign = false;
            }
        };

        this.textToSpeech.setOnUtteranceProgressListener(this.progressListener);
    }

    public void doStop() {
        this.doingSign =  true;
        this.textToSpeech.stop();

        for (int i = 0; i < 20; i++) {
            if (!doingSign) {
                break;
            } else {
                try {
                    Thread.sleep(100L);  // 最多等待2秒
                } catch (Exception e) {
                    LogUtil.info(TAG, "sleep fail", e);
                }
            }
        }
    }

    public void doPause() {
        this.doingSign =  true;
        this.textToSpeech.stop();

        for (int i = 0; i < 20; i++) {
            if (!doingSign) {
                String currentIdx = this.sharedPreferences.getString(CacheKey.CURRENT_IDX.name(), null);
                if (currentIdx == null) {
                    CacheUtil.writeMsg(this.sharedPreferences, false, "doPause 时，CURRENT_IDX缺失");
                    break;
                }
                String[] contents = CacheUtil.getContents(this.sharedPreferences);
                String currentText = contents[Integer.parseInt(currentIdx)];
//                String currentText = this.sharedPreferences.getString(CacheKey.CURRENT_TEXT.name(), "");
                if (currentText != null && !currentText.trim().isEmpty()) {
                    this.addFirst(new String[]{"" + currentIdx, currentText});
                }
                break;
            } else {
                try {
                    Thread.sleep(100L);  // 最多等待2秒
                } catch (Exception e) {
                    LogUtil.info(TAG, "sleep fail", e);
                }
            }
        }
    }

    /**
     * @param textAndIds 要添加到队尾的元素
     */
    public void addText(String[] textAndIds) {
        textQueue.add(textAndIds);
    }

    /**
     * @param textAndIds 要添加到队首的元素
     */
    public void addFirst(String[] textAndIds) {
        ((ArrayDeque<String[]> )this.textQueue).addFirst(textAndIds);
    }

    public void clearQueue() {
        this.textQueue.clear();
    }

    /**
     * 清空当前队列中当前章节内容
     * @return false:队列全空了; true:还有下一章;
     */
    public boolean clearCurrentItem() {
        while (true) {
            String[] textAndIds = this.textQueue.poll();
            if (textAndIds == null) {
                return false;
            }
            if (textAndIds.length == 7) {
                addFirst(textAndIds);
                return true;
            }
        }
    }

    public void matchQueueIdx(String[] contents, int idx, String currentId) {
        String[] textAndIds = this.textQueue.poll();
        int queIdx = Integer.parseInt(textAndIds[0]);  // queIdx为最后移出的idx
        if (textAndIds.length == 7 && !textAndIds[2].equals(currentId)) {
            // 先判断特殊情况,本章内容已经全部不在队列中了
            addFirst(textAndIds); // 这是下一章内容，需要加回去
            queIdx = contents.length - 1;  // 更新queIdx
        }

        if (queIdx >= idx) {
            // 队列需要补充 从queIdx包含 补到idx包含
            for (int i = queIdx; i >= idx; i--) {
                addFirst(new String[]{"" + i, contents[i]});
            }
        } else {
            // queIdx < idx 表示队列还没读取要播放的位置，需要移出一部分 从queIdx不包含 到idx不包含
            for (int i = queIdx + 1; i < idx; i++) {
                this.textQueue.poll();  // 移出
            }
        }
    }

    /**
     * 尝试播放下一段
     * @return true:成功播放; false:没有可播放内容
     */
    public boolean tryPlayNextText() {
        String[] textAndIds = this.textQueue.poll();
        if (textAndIds == null) {
            @SuppressLint("CommitPrefEdits") SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putBoolean(CacheKey.Show_PAUSE.name(), false);  // 队列没有内容了，播放也停止
            edit.apply();
            return false;
        }
        if (textAndIds[1].trim().isEmpty()) {
            return tryPlayNextText();
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            textToSpeech.speak(textAndIds[1], TextToSpeech.QUEUE_FLUSH, null, "uniqueId");
        } else {
            textToSpeech.speak(textAndIds[1], TextToSpeech.QUEUE_FLUSH, null);
        }

        SharedPreferences.Editor edit = this.sharedPreferences.edit();
        edit.putString(CacheKey.CURRENT_IDX.name(), textAndIds[0]);  // 更新缓存中当前播放的idx

        if (textAndIds.length == 7) {
            edit.putString(CacheKey.CURRENT_ID.name(), textAndIds[2]);  // 更新缓存中当前itemId
            edit.putString(CacheKey.CURRENT_TITLE.name(), textAndIds[3]);  // 当前标题
            edit.putString(CacheKey.CURRENT_CONTENT.name(), textAndIds[4]);  // 更新缓存中当前章节全部内容
            edit.putString(CacheKey.NEXT_ID.name(), textAndIds[5]);  //**// 更新缓存中下一章itemId
            edit.putString(CacheKey.PRE_ID.name(), textAndIds[6]);  // 更新缓存中上一章itemId

            edit.putString(CacheKey.REQ_ID.name(), textAndIds[5]);  // 更新准备缓存的id,触发缓存ID
            int reqInc = sharedPreferences.getInt(CacheKey.REQ_INC.name(), 1);
            reqInc++;
            edit.putInt(CacheKey.REQ_INC.name(), reqInc);
        }
        edit.apply();
        return true;
    }

}
